import React, { Component } from "react";
import "./css/index.css";

export default class App extends Component {
  myRef = React.createRef();
  state = {
    todoList: ["aa", "bb", "cc"],
  };
  render() {
    return (
      <>
        <div>10-todo-list</div>
        <div>
          <input type="text" ref={this.myRef} />
          <button type="button" onClick={(evt) => this.handleAdd()}>
            add
          </button>
        </div>
        <div>
          <ul>
            {this.state.todoList.map((item, index) => {
              return (
                <li key={item}>
                  {/* 直接展示 */}
                  {/* <span>{item}</span> */}

                  {/* 富文本 dangerouslySetInnerHTML 风险很高*/}
                  <span
                    dangerouslySetInnerHTML={{
                      __html: item,
                    }}
                  ></span>

                  <button
                    type="button"
                    onClick={(evt) => this.handleDel(index)}
                  >
                    del
                  </button>
                </li>
              );
            })}
          </ul>
          {/* 方案一 */}
          {/* {this.state.todoList.length === 0 ? <div>暂无代办事项</div> : null} */}

          {/* 方案二 */}
          {/* {this.state.todoList.length === 0 && <div>暂无代办事项</div>} */}

          {/* 方案三 */}
          {
            <div className={this.state.todoList.length !== 0 ? "hidden" : ""}>
              暂无代办事项
            </div>
          }
        </div>
      </>
    );
  }

  handleAdd = () => {
    if (!this.myRef.current.value) {
      return;
    }
    let arr = [...this.state.todoList];
    arr.push(this.myRef.current.value);
    this.setState({
      todoList: arr,
    });

    // 清空input
    this.myRef.current.value = "";
  };

  handleDel = (index) => {
    // 复制
    // let arr = this.state.todoList.slice();
    let arr = this.state.todoList.concat();
    // 删除元素
    arr.splice(index, 1);
    this.setState({
      todoList: arr,
    });
  };
}
